package com.tiny_wind.resource_manager.utility;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class GaJJwtManager {
	// 过期时间24h
	public static final long ms_expireTime = 24 * 60 * 60 * 1000;

	// token秘钥,设置的复杂点这里用一串uuid，并用HMAC256加密的
	private static final String ms_tokenSecret = "JFKDJFKGFGFGIFG8R9589589";
	
	public static final String ms_authKey = "Authorization";

	// 生成token
	public static String generatorToken(String userAccount, Integer userId) {
		// 过期时间
		Date date = new Date(System.currentTimeMillis() + ms_expireTime);
		// 秘钥及加密算法
		Algorithm algorithm = Algorithm.HMAC256(ms_tokenSecret);
		// 设置头部信息
		Map<String, Object> header = new HashMap<String, Object>(2);
		header.put("type", "JWT");
		header.put("alg", "HS256");
		// 附带用户信息，生成token
		return JWT.create().withHeader(header).withClaim("userName", userAccount).withClaim("userId", userId)
				.withExpiresAt(date).sign(algorithm);
	}

	/**
	 * 验证Token
	 * 
	 * @param token
	 * @return
	 * @throws Exception
	 */
	public static Map<String, Claim> verifyToken(String token) throws Exception {
		JWTVerifier verifier = JWT.require(Algorithm.HMAC256(ms_tokenSecret)).build();
		DecodedJWT jwt = null;
		try {
			jwt = verifier.verify(token);
		} catch (Exception e) {
			throw new RuntimeException("凭证已过期，请重新登录");
		}
		return jwt.getClaims();
	}

	/**
	     * 解析Token
	     * @param token
	     * @return
	     */
	    public static Map<String, Claim> parseToken(String token){
	        DecodedJWT decodedJWT = JWT.decode(token);
	        return decodedJWT.getClaims();
	    }
}
